<?php
namespace cmf\lib\interfaceauth;
use \Firebase\JWT\JWT;
use think\Config;

class InterfaceAuth
{
    
    /**
     * 
     *创建token 
     * @param $data     需要记录的数据
     * @param $aud      面向的用户  LOGIN 登录用户   api_auth接口鉴权
     * @param $expired  过期时间  默认7200秒 2小时
     * @return 返回令牌信息
     **/
    public static function createToken( $data = '' , $aud = 'LOGIN' , $expired = '2592000' )
    {
        $key = Config::get('sign_config.key');
        $currentTime = time();
        $options = [
            'iss'   => empty( $key ) ? 'dc52d2f5dxc': $key,//key值,如果未配置则使用乱码,使之无法解析
            'aud'   => $aud,//面向的用户 (login登录用户, api_auth接口鉴权
            'iat'   => $currentTime, //签发时间
            'nbf'   => time(),//JWT生效时间  (立即生效)
            'exp'   => time()+$expired,//过期时间 
            'data'  => $data //记录数据
        
        ];
        return JWT::encode( $options , Config::get( 'sign_config.key' ) , "HS256" );
    }
    
    /**
     * 验证token
     * @param $tokencode 令牌值
     * @return 验证成功返回记录的数据,否则返回空字符串
     * @exception 发生异常返回 Request denied  以及错误码
     **/
    public static function verificationToken( $tokencode )
    {
        $key = Config::get('sign_config.key');
        try {
            $options = JWT::decode( $tokencode , $key , [ 'HS256' ] ) ;
        } catch (\InvalidArgumentException $e ) {
            
            return [ 'status' => false , 'message'=>'Request denied' , 'code' => $e->getMessage() ];
        } catch (\UnexpectedValueException $e ) {
            
            return [ 'status' => false , 'message'=>'Request denied' , 'code' => $e->getMessage() ];
        } catch (\SignatureInvalidException $e ) {
            
            return [ 'status' => false , 'message'=>'Request denied' , 'code' => $e->getMessage() ];
        } catch (\BeforeValidException $e ) {
            
            return [ 'status' => false , 'message'=>'Request denied' , 'code' => $e->getMessage() ];
        } catch (\ExpiredException $e ) {
            
            return [ 'status' => false , 'message'=>'Request denied' , 'code' => $e->getMessage() ];
        }
        
        return isset( $options->data ) ? $options->data : '';
    }
    
    
    
}